package com.canyou.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Locale;

/**
 * spring上下文工具类
 *
 * @author fy
 * @date 20/03/24 11:51
 */
@Component
public class SpringContextUtils implements ApplicationContextAware, DisposableBean {

    private static final String DEV_PROFILE = "dev";
    private static final String TEST_PROFILE = "test";
    private static final String PRD_PROFILE = "prd";

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public void destroy() throws Exception {
        context = null;
    }

    /**
     * 通过name获取bean
     *
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     *
     * @param requiredType
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }

    /**
     * 国际化使用
     *
     * @param key
     * @return
     */
    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }

    /**
     * 获取当前环境
     *
     * @return
     */
    public static String[] getActiveProfiles() {
        return context.getEnvironment().getActiveProfiles();
    }

    /**
     * 是否是dev环境
     *
     * @return
     */
    public boolean isDev() {
        return Arrays.asList(getActiveProfiles()).contains(DEV_PROFILE);
    }

    /**
     * 是否是test环境
     *
     * @return
     */
    public boolean isTest() {
        return Arrays.asList(getActiveProfiles()).contains(TEST_PROFILE);
    }

    /**
     * 是否是prd环境
     *
     * @return
     */
    public boolean isPrd() {
        return Arrays.asList(getActiveProfiles()).contains(PRD_PROFILE);
    }

}
